﻿exports.addWildcard = addWildcard;
exports.getShell = getShell;
exports.getFif = getFif;
exports.getTempFile = getTempFile;

const {Cc, Ci, Cu} = require("chrome");
const {data} = require("sdk/self");

Cu.import("resource://gre/modules/FileUtils.jsm");
Cu.import("resource://gre/modules/Services.jsm");

const ResProtocolHandler = Services.io.getProtocolHandler("resource").QueryInterface(Ci.nsIResProtocolHandler);
const ChromeRegistry = Cc["@mozilla.org/chrome/chrome-registry;1"].getService(Ci.nsIChromeRegistry);

function resolveToFile(uri) {
    switch (uri.scheme) {
        case "chrome":
            return resolveToFile(ChromeRegistry.convertChromeURL(uri));
        case "resource":
            return resolveToFile(Services.io.newURI(ResProtocolHandler.resolveURI(uri), null, null));
        case "file":
            return uri.QueryInterface(Ci.nsIFileURL).file;
        default:
            throw new Error("Cannot resolve");
    }
}

function getTempFile(fileName)
{
    var file = FileUtils.getFile("TmpD", [fileName]);
    file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, FileUtils.PERMS_FILE);
    return file.path;
}

function getFif()
{
    let fif = data.url("fif.exe");
    fif = resolveToFile(Services.io.newURI(fif, null, null));
    console.log(fif.path);

    // var localFile = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile);
    // localFile.initWithPath(exe.path);

    var process = Cc["@mozilla.org/process/util;1"].createInstance(Ci.nsIProcess);
    process.init(fif);
    return process;
}

function getShell()
{
    var env = Cc["@mozilla.org/process/environment;1"].getService(Ci.nsIEnvironment);
    var shell = new FileUtils.File(env.get("COMSPEC"));
    var process = Cc["@mozilla.org/process/util;1"].createInstance(Ci.nsIProcess);
    process.init(shell);

    return process;
}

function addWildcard(path)
{
    var temp = path.slice(-1);
    if ("*" !== temp)
    {
        if ("\\" !== temp && "/" !== temp)
        {
            temp = path + "\\";
        }

        temp += "*.*";
    }
    else
    {
        temp = path;
    }

    return temp;
}
